package utils;

import java.io.*;
import java.net.*;

/**
 * @Description TODO
 * @Author hhy
 * @Date 2020/9/23 19:18
 */
public class DownloadImage {
    public void downImage(String urlStr,String path,String filename) throws IOException {
        URL url = new URL(urlStr);
        //这里是可以设置代理的
        HttpURLConnection conn = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 1080)));
        //设置超时时间 5s
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //设置引用来源，可有可无的设置，但是我这里还是设置一下
        conn.setRequestProperty("referer","https://www.pixiv.net/artworks/84430212");
        conn.setRequestProperty("cookie","");

        //从IO流中拿到数据
        InputStream in = conn.getInputStream();
        byte[] getData = readInputStream(in);

        //文件的保存位置 如果文件不存在的话，那就创建一个
        File fileDir = new File(path);
        if (!fileDir.exists()){
            fileDir.mkdir();
        }

        File file = new File(fileDir + File.separator + filename);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        //关闭流
        if (fos!=null) fos.close();
        if (in!=null) in.close();

        System.out.println("文件下载成功。。。。");


    }

    //从输入流中读取字节
    private byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
}
